from datetime import datetime

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect
from app01.models import Article
from app01.models import User_Article_Like
from app01.utils.form import AddArticle
from app01.models import ReplyArticle
import app01.svm
from app01.utils.pagination import Pagination


# Create your views here.


def article(request):
    coo = request.session.get('info', "")
    if request.method == 'GET':
        queryset = Article.objects.all().order_by("-likes")[:15]
        hot_queryset = Article.objects.all().order_by("-likes")[:10]
        return render(request, "article/article_main.html",
                      {"queryset": queryset, "hot_queryset": hot_queryset, "order": (i for i in range(0, 10)),
                       'coo': coo})


def article_read(request, id):
    coo = request.session.get('info', "")
    read_article = Article.objects.filter(id=id).first()
    articlereply = ReplyArticle.objects.filter(article_id_id=id)
    mainreeply = articlereply & ReplyArticle.objects.filter(replyarticle_id=False)  # 子评论
    manreply = articlereply & ReplyArticle.objects.filter(reply_reply_id__isnull=True)  # 主评论
    dic = {}
    for obj in manreply:
        reply = mainreeply & ReplyArticle.objects.filter(reply_reply_id=obj.id).order_by("release_time")
        lis = []
        for i in reply:
            if i.user_id is not None:
                lis.append((i.user_id.name,
                            (articlereply & ReplyArticle.objects.filter(id=i.replytiezi_id)).first().user_id.name,
                            i.content))
            else:
                continue
        dic[obj] = lis
    return render(request, "article/article.html", {"coo": coo, "read_article": read_article, "dic": dic})


def article_show(request, type):
    coo = request.session.get('info', "")
    if request.method == 'GET':
        show_article = Article.objects.all()
        page_object = Pagination(request, show_article)
        context = {
            'coo': coo,
            "show_article": page_object.page_queryset,
            "page_string": page_object.html()
        }
        return render(request, "article/article_show.html", context)


def article_add(request):
    coo = request.session.get('info', "")
    if request.method == 'GET':
        form = AddArticle()
        return render(request, "article/article_add.html", {'coo': coo, 'form': form})

    form = AddArticle(data=request.POST)
    print(request.POST)
    if form.is_valid():
        form.instance.user_id_id = request.session["info"]["id"]
        form.instance.release_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        form.save()
        return redirect("/article/")


def article_edit(request, id):
    coo = request.session.get('info', "")
    row_object = Article.objects.filter(id=id).first()
    if request.method == 'GET':
        form = AddArticle(instance=row_object)
        return render(request, "article/article_edit.html", {"form": form, 'coo': coo})
    form = AddArticle(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/me/fabu/article/")


def article_delete(request):
    uid = request.GET.get('uid')
    exists = Article.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({"status": False, 'error': "删除失败，数据不存在。"})

    Article.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


def article_likes(request):
    coo = request.session.get('info', "")
    uid = coo["id"]
    id = request.GET.get('id')
    exists = User_Article_Like.objects.filter(user_id_id=uid, like_id_id=id).exists()
    if not exists:
        User_Article_Like.objects.create(user_id_id=uid, like_id_id=id,
                                         like_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        likes = Article.objects.filter(id=id).first().likes + 1
        print(likes)
        Article.objects.filter(id=id).update(likes=likes)
        return JsonResponse({"status": True, 'error': "点赞成功"})
    likes = Article.objects.filter(id=id).first().likes - 1
    Article.objects.filter(id=id).update(likes=likes)
    User_Article_Like.objects.filter(user_id_id=uid, like_id_id=id).delete()
    return JsonResponse({"status": True, 'error': "已取消点赞"})


@csrf_exempt
def pl(request):
    coo = request.session.get('info', "")
    data = request.POST
    article_id = data.get("article_id", "")
    content = data.get('content', "")
    if article_id == "" or content == "":
        return JsonResponse({"status": False, "error": "不可为空"})
    ReplyArticle.objects.create(article_id_id=article_id, user_id_id=coo["id"], content=content,
                                release_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    comments = Article.objects.filter(id=article_id).first().comments + 1
    Article.objects.filter(id=article_id).update(comments=comments)
    return JsonResponse({"status": True})
